<template>
  <el-dialog :model-value="true" title="选择标签" :width="600" :height="600" center align-center destroy-on-close @close="onClose">
    <el-form :model="params" inline label-width="80px">
      <el-form-item label="标签名称">
        <el-input v-model="params.tagName" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query()"> 查询</el-button>
        <el-button @click="resetQuery()">重置</el-button>
      </el-form-item>
    </el-form>
    <div v-loading="loading">
      <el-check-tag v-for="item in listData" :key="item.id" :value="item.id" :checked="selectTags.hasOwnProperty(item.id)" type="primary" class="tagItem" @change="onChange($event, item)">
        {{ item.tagName }}
      </el-check-tag>
    </div>
    <template #footer>
      <el-button @click="onClose">取消</el-button>
      <el-button type="primary" @click="onSubmit()"> 确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
  import { onMounted, ref } from 'vue'
  import { ElCheckTag, ElMessage } from 'element-plus'
  import { commonApi } from '@/api/common'

  const props = defineProps({
    tags: {
      type: Array,
      default: () => []
    }
  })

  const loading = ref(false)
  const listData = ref([])
  const params = ref({})
  const resetQuery = () => {
    params.value = {}
    query()
  }
  const query = async () => {
    loading.value = true
    listData.value = await commonApi.tagList(params.value)
    loading.value = false
  }

  onMounted(() => {
    // 处理选中
    if (props.tags && props.tags.length > 0) {
      props.tags.forEach((item) => {
        selectTags.value[item.id] = item
      })
    }

    // 查询
    query()
  })

  // 选择
  const selectTags = ref({})
  const onChange = (event, item) => {
    if (event) {
      selectTags.value[item.id] = item
    } else {
      delete selectTags.value[item.id]
    }
  }

  // 处理回调
  const emit = defineEmits(['close'])
  const onSubmit = () => {
    const selectedRows = Object.values(selectTags.value)
    if (selectedRows.length < 1) {
      ElMessage.error({
        message: '请选择标签',
        grouping: true
      })
      return
    }
    emit('close', selectedRows)
  }

  const onClose = () => {
    emit('close')
  }
</script>

<style scoped lang="scss">
  .tagItem {
    box-sizing: border-box;
    height: 32px;
    margin: 5px;
    padding: 0 15px;
    line-height: 32px;
  }
</style>
